package com.ibm.db2oncampus.portal.framework.orm.hibernate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Filterable;
import org.hibernate.util.StringHelper;

/**
 * 
 * @author Wellington
 *
 */
public class LocalSessionFactoryBean extends org.springframework.orm.hibernate3.LocalSessionFactoryBean {

	private List localFilters;
	private List filters;
	
	public LocalSessionFactoryBean() {
		localFilters = new ArrayList();
		filters = new ArrayList();
	}

	protected void postProcessConfiguration(Configuration config) throws HibernateException	{
		addFiltersToCollections(config, localFilters);
		addFiltersToCollections(config, filters);
	}

	private void addFiltersToCollections(Configuration config, List filters) {
		FilterFactoryBean filter;
		for(Iterator i$ = filters.iterator(); i$.hasNext(); addFiltersToCollections(config, filter.getName(), filter.getAssociationFilters()))
		{
			filter = (FilterFactoryBean)i$.next();
			org.hibernate.mapping.PersistentClass persistentClass = config.getClassMapping(filter.getName());
			addFilters(persistentClass, filter.getFilters());
		}

	}

	private void addFiltersToCollections(Configuration config, String owner, List filters) {
		FilterFactoryBean associationFilter;
		org.hibernate.mapping.Collection collection;
		for(Iterator i$ = filters.iterator(); i$.hasNext(); addFilters(collection, associationFilter.getFilters()))
		{
			associationFilter = (FilterFactoryBean)i$.next();
			collection = config.getCollectionMapping(getRole(owner, associationFilter.getName()));
		}

	}

	private void addFilters(Filterable filterable, Map filterMap) {
		java.util.Map.Entry entry;
		for(Iterator i$ = filterMap.entrySet().iterator(); i$.hasNext(); filterable.addFilter((String)entry.getKey(), (String)entry.getValue()))
			entry = (java.util.Map.Entry)i$.next();

	}

	private String getRole(String className, String path) {
		return StringHelper.qualify(className, path);
	}

	public void setLocalFilters(List localFilters) {
		this.localFilters = localFilters;
	}

	public void setFilters(List filters) {
		this.filters = filters;
	}
}